package com.calvin.study.service.sys.security;

import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.calvin.study.mapper.sys.SysUserMapper;
import com.calvin.study.model.sys.SysUser;

@Service
public class MyUserDetailsService implements UserDetailsService {

	@Resource
	SysUserMapper sysUserMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		SysUser sysUser = sysUserMapper.findByUserName(username);
		if(null == sysUser) {
			throw new UsernameNotFoundException("该用户不在");
		}
		//查询该用户拥有的角色
		List<String> roleCodes = sysUserMapper.findRoleByUserName(username);
		//该用户角色对应的权限资源集合
		List<String> authorities = sysUserMapper.findAuthByRoleCodes(roleCodes);

		// 在每个rolecode前面添加上"ROLE_"，最终"ROLE_admin"
		roleCodes = roleCodes.stream().map(rc -> "ROLE_" + rc).collect(Collectors.toList());
		
		authorities.addAll(roleCodes);
		List<GrantedAuthority> gauthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", authorities));
		User user = new User(sysUser.getUserName(), sysUser.getPassword(), sysUser.getEnabled(), true, true, true, gauthorities);
		return user;
	}

}
